package com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.base.remote.RemoteService;
import com.css.fxfzxczh.base.response.RestResponse;
import com.css.fxfzxczh.common.utils.BeanUtil;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.SamPoiHouSur;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.repository.SamPoliHouSurRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.vo.BuildGridFindAllVo;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.entity.FxqhBuildingGridDataVersion;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.entity.JcFault;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.param.QueryParam;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.repository.SeismicIntensityDrawRepository;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.vo.ResultVO;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.vo.SamPoiHouSurVO;
import com.css.fxfzxczh.modules.seismicIntensityMap.seismicIntensityDraw.vo.VersionPageVO;
import com.css.fxfzxczh.util.PlatformObjectUtils;

import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年06月21日  15:22
 */
@Service
public class SeismicIntensityDrawService {

    @Resource
    SeismicIntensityDrawRepository seismicIntensityDrawRepository;
    @Resource
    SurTaskManageRepository surTaskManageRepository;
    @Resource
    SamPoliHouSurRepository samPoliHouSurRepository;
    @Value("${jcsj.url}")
    private String jcsjUrl;
    @Value("${basicData.url}")
    private String basicDataUrl;
    @Resource
    RemoteService remoteService;

    public ResultVO getSelectedData(QueryParam queryParam) {
        ResultVO vo = new ResultVO();
        //地震事件id
        String xsemId = queryParam.getXsemId();
        //获取要查询的项
        String selectedItem = queryParam.getSelectedItem();
        List<String> strings = Arrays.asList(selectedItem.split(","));
        //根据地震事件查询关联的评估子区 1和2表示要查询抽样点和补充抽样点信息
        if(strings.contains("1") || strings.contains("2")){
            List<SurTaskManage> allData = surTaskManageRepository.getAllData(xsemId,"");
            if(PlatformObjectUtils.isNotEmpty(allData)){
                //抽样点
                if(strings.contains("1")){
                    List<String> xstmIdList = allData.stream().filter(surTaskManage -> {
                        return "1".equals(surTaskManage.getType());
                    }).map(SurTaskManage::getXstmId).collect(Collectors.toList());
                    //根据评估子区获取对应的抽样点房屋信息
                    List<SamPoiHouSurVO> samPoiHouSurList = getSamPoiHouSurList(xstmIdList);
                    vo.setSamPoiHouSurVOList(samPoiHouSurList);
                }
                //补充抽样点
                if(strings.contains("2")){
                    List<String> xstmIdList = allData.stream().filter(surTaskManage -> {
                        return "2".equals(surTaskManage.getType());
                    }).map(SurTaskManage::getXstmId).collect(Collectors.toList());
                    List<SamPoiHouSurVO> samPoiHouSurList = getSamPoiHouSurList(xstmIdList);
                    vo.setReplenishSamPoiHouSurVOList(samPoiHouSurList);
                }
            }

        }
        //断层
        if(strings.contains("4")){
            String url = jcsjUrl + "/datacenter/sysDataVersion/queryAllByVersionCode?versionCode="+queryParam.getFaultVersion()+"&typeCode=dc";
            JSONObject valueMap = new JSONObject();
            JSONObject jsonObject = (JSONObject) remoteService.getJCSJ(url, 2, valueMap).getData();
            String arrObj = jsonObject.getString("data");
            List<JcFault> faultList = JSON.parseArray(arrObj, JcFault.class);
            vo.setFaultList(faultList);
        }
        //关联大区划的13张表数据 房屋基础信息数据
        if(strings.contains("6")){
            String url = basicDataUrl + "buildingGridDataVersion/xczh/listGridDataByVersionCode?version="+queryParam.getHouseVersion()+"&type=czghjggw";
            JSONObject valueMap = new JSONObject();
            valueMap.put("version", queryParam.getHouseVersion());
            valueMap.put("type", "czghjggw");
            JSONArray jSONArray = (JSONArray) remoteService.getJCSJ(url, 3, valueMap).getData();
            List<BuildGridFindAllVo> buildingGridDataVersionList = JSON.parseArray(jSONArray.toJSONString(), BuildGridFindAllVo.class);
            vo.setBuildGridList(buildingGridDataVersionList);
        }
        //高程
        if(strings.contains("7")){
            String url = jcsjUrl + "/datacenter/sysDataVersion/versionCode/"+queryParam.getDemVersion();
            JSONObject valueMap = new JSONObject();
            JSONObject jsonObject = (JSONObject) remoteService.getJCSJ(url, 2, valueMap).getData();
            String dataFileIds = jsonObject.getString("dataFileIds");
            if(StringUtils.isNotBlank(dataFileIds)){
                String[] split = dataFileIds.split(",");
                url = jcsjUrl + "/attachment/details?id=" + split[0];
                RestResponse jcsj = remoteService.getJCSJ(url, 2, valueMap);
                JSONObject data =(JSONObject) jcsj.getData();
                vo.setDemPath(data.getString("fileDirId")+data.getString("attachPath"));
            }
        }
        return vo;
    }
    private List<SamPoiHouSurVO> getSamPoiHouSurList(List<String> xstmIdList){
        List<SamPoiHouSur> samPoiHouSurList = samPoliHouSurRepository.getHouseDataBySurTaskManageId(xstmIdList);
        List<SamPoiHouSurVO> samPoiHouSurVOS = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(samPoiHouSurList)){
            samPoiHouSurList.forEach(entity->{
                SamPoiHouSurVO samPoiHouSurVO = new SamPoiHouSurVO();
                BeanUtil.copyPropertiesIgnoreEmpty(entity,samPoiHouSurVO);
                samPoiHouSurVOS.add(samPoiHouSurVO);
            });
        }
        return samPoiHouSurVOS;
    }

    public List<FxqhBuildingGridDataVersion> get13TableVersionList(Integer rows, Integer page) {
        String url = basicDataUrl + "buildingGridDataVersion/xczh/list";
        JSONObject valueMap = new JSONObject();
        valueMap.put("rows",rows);
        valueMap.put("page",page);
        JSONArray JSONArray = (JSONArray) remoteService.getJCSJ(url, 3, valueMap).getData();
        List<FxqhBuildingGridDataVersion> fxqhBuildingGridDataVersions = JSONObject.parseArray(JSONArray.toJSONString(), FxqhBuildingGridDataVersion.class);
        String arrObj = null;
        return fxqhBuildingGridDataVersions;
    }

    public RestResponse getParam1Version(String tab, VersionPageVO vo) {
        vo.setTypeCode(null);
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("sjxtRestUrl") + "/datacenter/sysDataVersion/page?hasNationwide=1";
        Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(vo), Map.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }
        }
        if (PlatformObjectUtils.isNotEmpty(vo.getProvince())) {
            url = url + "&dataRangeProvince = " + vo.getProvince();
        } else {
            url = url + "&dataRangeProvince = -1";

        }
        if (PlatformObjectUtils.isNotEmpty(vo.getVersionCode())) {
            url = url + "&versionCode = " + vo.getVersionCode();
        }
        if (PlatformObjectUtils.isNotEmpty(vo.getUploadStartTime())) {
            url = url + "&uploadStartTime = " + vo.getUploadStartTime();
        }
        if (PlatformObjectUtils.isNotEmpty(vo.getUploadEndTime())) {
            url = url + "&uploadEndTime = " + vo.getUploadEndTime();
        }
        if (PlatformObjectUtils.isNotEmpty(vo.getUploadUsername())) {
            url = url + "&uploadUsername = " + vo.getUploadUsername();
        }

        RestResponse jcsjPage = null;
        JSONObject valueMap = new JSONObject();
        switch (tab) {
            case "1"://断层
                url = url + "&typeCode=dc";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "2"://高程
                url = url + "&typeCode=demgcsj";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "3"://地层岩性
                url = url + "&typeCode=dcyx1";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "4"://道路
                url = url + "&typeCode=dl1";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "5"://地震动峰值加速度数据（50年超越概率2%）
                url = url + "&typeCode=pga002";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "6"://地震动峰值加速度数据（50年超越概率10%）
                url = url + "&typeCode=pga010";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "7"://地震动峰值加速度数据（50年超越概率63%）
                url = url + "&typeCode=pga063";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
            case "8"://中国地震综合等震线
                url = url + "&typeCode=dzzhdzx1";
                jcsjPage = remoteService.getJCSJ(url, 2,valueMap);
                break;
        }
        return jcsjPage;
    }
}
